import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useUserStore } from './user'
import { addHandler } from '@/api/ws'
import { fileMd5, strMd5 } from '@/utils/md5'
import { message } from 'ant-design-vue'
import { 
    sendTextMessage,
    sendImageMessage,
    sendMessageReadAck,
} from '@/api/ws'
import { 
    getSessions, 
    getSessionMessages,
    addFavorite
 } from '@/api/message'
import { uploadObject, doesObjectExist } from '@/api/file'
import { getUserInfo } from '@/api/user'
import { v4 as uuidv4 } from 'uuid'

export const useChatStore = defineStore('chat', () => {
    // 聊天相关状态
    //   user自己的信息从userStore中获取
    //   const user = ref({ id: 1, name: '我', avatar: '...' }) 
    // 默认表情
    const emojis = ref([
        '😀','😁','😂','🤣','😃','😄','😅','😆','😉','😊','😍','😘','😜','🤔','😭','😱','👍','🙏','🎉',
        '😋','😎','😏','😒','😓','😔','😖','😘','😚','😜','😝','😞','😠','😡','😢','😣','😤','😥','😦','😧','😨','😩','😪','😫','😬','😭','😮','😯','😰','😱','😲','😳','😴','😵','😶','😷','🙁','🙂','🙃','🙄','🤐','🤑','🤒','🤓','🤔','🤕','🤠','🤡','🤢','🤣','🤤','🤥','🤧','🤨','🤩','🤪','🤫','🤬','🤭','🤮','🤯','🥰','🥳','🥴','🥺','🧐','🧑‍💻','👻','💀','👽','👾','🤖','😺','😸','😹','😻','😼','😽','🙀','😿','😾'
      ])
    const loading = ref(false)

    // 关注我的用户信息
    const followers = ref([])
    // 我关注的用户信息
    const following = ref([])
    // 互相关注的用户信息
    const mutualFollowers = ref([])

    
    const userinfo = ref({
        email: '',
        name: '',
        avatar: ''
    })
    // 收藏的自定义表情
    const favoriteEmojis = ref([])
    // 缓存好友的信息，用户的头像，昵称，邮箱
    const friends = ref(new Map())
    // 会话列表
    /*
        { 
            id: "001", 
            name: '小明', 
            is_group: false,
            avatar: '...', 
            lastMsg: '', 
            unread: 0,
            updated_at: 1324567890,
            is_pinned: false 
        }
    */
    const sessionList = ref([])
    const sessionTotal = ref(0)
    const sessionPage = ref(1)
    const sessionPageSize = ref(20)
    // 新增：会话加载状态
    // 根据sessionTotal和sessionPage计算
    const hasMoreSessions = computed(() => sessionPage.value * sessionPageSize.value < sessionTotal.value)
    const loadingMoreSession = ref(false)
    // 消息列表
    /*
    "001": [
        {
                id: "001", 
                from_id: '小明@qq.com',
                send_at: 1324567890,
                type: "text",
                text: "你好",
                image: {
                    id: "001",
                    content: "这是一张图片",
                },
                file: {
                    id: "001",
                    name: "test.txt",
                    size: 1024
                },
                // 这个字段是用户维护的，用于显示消息状态 sending send read error
                status: 'read'// 这个字段是用户维护的，用于显示消息状态
        }
    ]
    */
    const messagesMap = ref({})
    const messagesPageSize = ref(10)
    // 消息总页数和页码
    const messagesTotalAndPage = ref(new Map())
    // 最后一条消息
    const lastMessages = computed(() => {
        const result = {}
        for (const sessionid in messagesMap.value) {
            const msgs = messagesMap.value[sessionid]
            let lastMsg = ""
            if (msgs && msgs.length > 0) {
                lastMsg = msgs[msgs.length - 1]
                if (lastMsg.type === "text") {
                    lastMsg = lastMsg.text
                } else if (lastMsg.type === "image") {
                    lastMsg = "[图片]"
                }
            }
            result[sessionid] = lastMsg
        }
        return result
    })
    // 当前会话ID
    const activeId = ref('')

    // 当前会话消息列表
    const activeMessages = computed(() => messagesMap.value[activeId.value] || [])

    // 新增：会话加载状态
    // 记录各会话最后一条已读消息 id
    const lastReadIdMap = ref(new Map())

    // 根据最后已读消息动态计算未读数
    const unreadCounts = computed(() => {
        const result = {}
        for (const session of sessionList.value) {
            const sid = session.id
            const msgs = messagesMap.value[sid] || []
            if (msgs.length === 0) {
                result[sid] = 0
                continue
            }
            const lastReadId = lastReadIdMap.value.get(sid)
            if (!lastReadId) {
                // 没记录已读，全部未读
                result[sid] = msgs.length
            } else {
                const idx = msgs.findIndex(m => m.id === lastReadId)
                result[sid] = idx === -1 ? msgs.length : Math.max(0, msgs.length - (idx + 1))
            }
        }
        return result
    })

    // 操作方法

    
    function RecvMessageCallback(message) {
        console.log('RecvMessageCallback', message)
        
        // 确保会话存在
        const sessionId = message.session_id
        if (!messagesMap.value[sessionId]) {
            messagesMap.value[sessionId] = []
        }
        
        // 检查消息是否已存在（防止重复）
        const existingMsg = messagesMap.value[sessionId].find(m => 
            m.message_id === message.message_id || m.id === message.message_id)
        
        if (!existingMsg) {
            // 添加新消息
            const newMsg = {
                id: message.message_id,
                message_id: message.message_id,
                session_id: message.session_id,
                from_id: message.from_id,
                send_at: message.sent_at,
                type: message.text ? 'text' : 'image',
                text: message.text,
                image: message.image,
                status: 'received'
            }
            
            messagesMap.value[sessionId].push(newMsg)
            
            // 更新会话的最后消息
            const session = sessionList.value.find(s => s.id === sessionId)
            if (session) {
                session.lastMsg = message.text || '[图片]'
                session.time = Date.now()
                // 更新会话顺序
                updateSessionOrder(sessionId)
            }
            
            // 如果是当前会话，自动发送已读回执
            if (sessionId === activeId.value) {
                sendMessageReadAck(userinfo.value.email, sessionId, message.message_id)
                // 更新本地最后已读ID
                lastReadIdMap.value.set(sessionId, message.message_id)
            }
        }
    }
    function RecvSendAckCallback(ack) {
        console.log('RecvSendAckCallback', ack)
        // 查找对应的消息并更新状态
        const sessionId = ack.session_id
        const requestId = ack.request_id
        
        if (messagesMap.value[sessionId]) {
            const msgIndex = messagesMap.value[sessionId].findIndex(m => m.id === requestId)
            if (msgIndex !== -1) {
                // 更新消息状态为已发送
                messagesMap.value[sessionId][msgIndex].status = 'sent'
                // 更新消息ID为服务器返回的ID
                messagesMap.value[sessionId][msgIndex].message_id = ack.message_id
            }
        }
    }
    function RecvReadAckCallback(ack) {
        console.log('RecvReadAckCallback', ack)
        // 更新最后已读消息ID
        const sessionId = ack.session_id
        const messageId = ack.message_id
        
        // 更新最后已读消息ID
        lastReadIdMap.value.set(sessionId, messageId)
        
        // 更新消息状态为已读
        if (messagesMap.value[sessionId]) {
            // 找到该消息及之前的所有消息，将状态更新为已读
            const msgIndex = messagesMap.value[sessionId].findIndex(m => 
                (m.id === messageId || m.message_id === messageId))
            
            if (msgIndex !== -1) {
                // 更新该消息及之前的所有消息状态为已读
                for (let i = 0; i <= msgIndex; i++) {
                    // 只更新自己发送的消息状态
                    if (messagesMap.value[sessionId][i].from_id === userinfo.value.email) {
                        messagesMap.value[sessionId][i].status = 'read'
                    }
                }
            }
        }
    }
    async function fetchSessionMessages(sessionId) {
        try {
            if (messagesTotalAndPage.value.get(sessionId) === undefined) {
                messagesTotalAndPage.value.set(sessionId, {
                    total: 0,
                    page: 1
                })
            }
            if (messagesMap.value[sessionId] === undefined) {
                messagesMap.value[sessionId] = []
            }
            if (messagesTotalAndPage.value.get(sessionId).total !== 0 && messagesTotalAndPage.value.get(sessionId).page * 
                    messagesPageSize.value >= messagesTotalAndPage.value.get(sessionId).total) {
                return
            }
            const {messages, total} = await getSessionMessages(sessionId, messagesTotalAndPage.value.get(sessionId).page, messagesPageSize.value)
            // 头插到对应的会话中
            messagesMap.value[sessionId] = [...messages, ...messagesMap.value[sessionId]]
            messagesTotalAndPage.value.get(sessionId).total = total
            messagesTotalAndPage.value.get(sessionId).page++
            // 收集本批消息中缺失的好友邮箱，批量并行请求
            const missingEmails = []
            for (const message of messages) {
                if (!friends.value.has(message.from_id) && message.from_id !== userinfo.value.email) {
                    if (!missingEmails.includes(message.from_id)) {
                        missingEmails.push(message.from_id)
                    }
                }
            }
            if (missingEmails.length) {
                await Promise.all(missingEmails.map(email => fetchFriends(email)))
            }
        } catch (error) {
            console.error('获取会话消息失败', error)
            message.error('获取会话消息失败', error)
        }
    }
    async function fetchSessionList() {
        if (loadingMoreSession.value) return
        loadingMoreSession.value = true
        try {
            // 请求会话列表
            const {sessions, total} = await getSessions(sessionPage.value, sessionPageSize.value)
            // 追加到sessionList.value中
            sessions.forEach(session => {
                if (!sessionList.value.find(item => item.id === session.id)) {
                    sessionList.value.push({
                        id: session.id,
                        name: session.name,
                        avatar: session.avatar,
                        lastMsg: session.lastMsg,
                        unread: session.unread,
                        updated_at: session.updated_at,
                        is_pinned: session.is_pinned
                    })
                }
            })
            sessionTotal.value = total
            // 并行请求各会话的消息，提高加载速度
            await Promise.all(
                sessionList.value.map(s => fetchSessionMessages(s.id))
            )
        } catch (error) {
            console.error('获取会话列表失败', error)
            throw error
        }finally{
            loadingMoreSession.value = false
        }
    }
    // 当用户滚到最底部时，加载更多会话
    function handleScrollToBottom() {
        if (hasMoreSessions.value) {
            sessionPage.value++
            fetchSessionList()
        }
    }
    async function fetchFriends(email) {
        try {
            const userinfo = await getUserInfo(email)
            // 去重追加到friends.value中
            friends.value.set(userinfo.email, userinfo)
        } catch (error) {
            console.error('获取好友信息失败', error)
            message.error('获取好友信息失败', error)
        }
    }
    function handleSelectSession(id) {
        activeId.value = id
        // 默认出现在会话列表中的，一定在sessionlist中，因为会话列表就是通过这个list渲染的
        // const session = sessionList.value.find(s => s.id === id)

        // 获取最后一条消息 id
        const msgs = messagesMap.value[id] || []
        if (unreadCounts.value[id] > 0) {
            const lastMessageId = msgs[msgs.length - 1].message_id || msgs[msgs.length - 1].id
            // 通过 websocket 发送已读 ack
            sendMessageReadAck(userinfo.value.email, id, lastMessageId)
            // 更新本地最后已读 id
            lastReadIdMap.value.set(id, lastMessageId)
        }
    }

    function handleSendMessage(msg) {
        const newMessage = {
            id: uuidv4(),
            from_id: userinfo.value.email,
            text: msg,
            send_at: new Date().getTime(),
            type: 'text',
            status: 'sending'  // 初始状态为发送中
        }
        // 通过websocket接口发送消息
        // sendMessage(newMessage)
        messagesMap.value[activeId.value].push(newMessage)
        
        // 更新会话的最后消息
        const session = sessionList.value.find(s => s.id === activeId.value)
        if (session) {
            session.lastMsg = msg
            session.time = Date.now() // 添加时间戳用于排序
            // 更新会话顺序
            updateSessionOrder(activeId.value)
        }
        
        // 发送消息
        sendTextMessage(newMessage.id, userinfo.value.email, activeId.value, msg)
        
        // 更新最后已读消息ID（发送消息时，该消息应该被标记为已读）
        lastReadIdMap.value.set(activeId.value, newMessage.id)
    }
    function handleResend(msg) {
        // 删掉messagesMap.value[activeId.value]中status为sending的
        messagesMap.value[activeId.value] = messagesMap.value[activeId.value].filter(m => m.status !== 'sending')
        // 根据消息的类型，重新发送
        if (msg.type === 'text') {
            handleSendMessage(msg.text)
        } else if (msg.type === 'image') {
            handleSendImage(msg.image)
        }
    }

    async function handleSendImage(image) {
        // 如果image是一个二进制的文件内容，就先上传
        console.log(handleSendImage);
        if (image instanceof ArrayBuffer) {
            // 获取文件的md5值
            try{
                const id = await fileMd5(new Uint8Array(image))
                let path = ''
                // 查看文件是否存在
                const result = await doesObjectExist(id)
                if (result.exist) {
                    path = result.path
                }else {
                    // 上传文件
                    path = await uploadObject(new Uint8Array(image))
                }
                image = {
                    id: id,
                    path: path
                }
            }catch(err) {
                message.error("上传图片失败",err);
                return ;
            }
        }
        const tempId = uuidv4();
        const newMessage = {
            id: tempId,
            session_id: activeId.value,
            from_id: userinfo.value.email,
            image: {
                id: image.id,
                path: image.path
            },
            send_at: new Date().getTime(),
            type: 'image',
            status: 'sending'  // 初始状态为发送中
        }
        messagesMap.value[activeId.value].push(newMessage)
        
        // 更新会话的最后消息
        const session = sessionList.value.find(s => s.id === activeId.value)
        if (session) {
            session.lastMsg = '[图片]'
            session.time = Date.now() // 添加时间戳用于排序
            // 更新会话顺序
            updateSessionOrder(activeId.value)
        }
        
        // 发送消息
        sendImageMessage(newMessage.id, userinfo.value.email, activeId.value, image.id, image.path)
        
        // 更新最后已读消息ID（发送消息时，该消息应该被标记为已读）
        lastReadIdMap.value.set(activeId.value, newMessage.id)
    }
    async function handleAddFavorite(favorite) {
        let id = ''        
        let path = ''
        // 判断favorite是否是文件二进制数据还是一个路径
        //判断是二进制文件
        if (favorite instanceof ArrayBuffer) {
            // 如果是文件二进制数据，则执行文件上传逻辑
            //计算文件的md5作为文件的key，
            id =  await fileMd5(new Uint8Array(favorite))
            const result = await doesObjectExist(id)
            if (result.exist) {
                path = result.path
            } else {
                path = await uploadObject(fileId, favorite);
            }
            // 得到文件的路径之后，调用addFavorite接口
            const { success, msg } = await addFavorite(path);
            console.log(success, msg)

            if (!success) {
                message.error(msg)
                return
            }
        } else  {
            // 如果是路径，则执行图片上传逻辑
            // 直接调用addFavorite接口
            id = favorite.id
            path = favorite.path
            const { success, msg } = await addFavorite(path);
            console.log(success,msg);
            if (!success) {
                message.error(msg)
                return
            }
        } 

        // 添加自定义表情
        favoriteEmojis.value.push({
            type: 'image',
            id: id,
            path: path
        })
        message.success('添加收藏表情成功')
    }
    function handleSendFavorite(favorite) {
        // 通过websocket接口发送收藏表情
        // sendFavorite(favorite)
        messagesMap.value[activeId.value].push({
            email: Date.now(),
            from: user.value.id,
            image: {
                id: favorite.id,
                path: favorite.path
            },
            time: new Date().toLocaleTimeString(),
            type: 'favorite'
        })
    }


    // 新增：加载更多消息
    async function loadMoreMessages(sessionId = null) {
        try {
            const targetSessionId = sessionId || activeId.value
            if (!targetSessionId) {
                console.warn('没有指定会话ID，无法加载更多消息')
                return { success: false, message: '没有指定会话ID' }
            }
            
            // 检查是否还有更多消息可以加载
            const sessionPageInfo = messagesTotalAndPage.value.get(targetSessionId)
            if (sessionPageInfo && sessionPageInfo.total !== 0 && 
                sessionPageInfo.page * messagesPageSize.value >= sessionPageInfo.total) {
                return { success: false, message: '没有更多消息了' }
            }
            
            // 调用现有的fetchSessionMessages函数来加载更多消息
            await fetchSessionMessages(targetSessionId)
            
            return { 
                success: true, 
                message: '加载成功',
                hasMore: sessionPageInfo && sessionPageInfo.total > sessionPageInfo.page * messagesPageSize.value
            }
        } catch (error) {
            console.error('加载更多消息失败', error)
            return { success: false, message: '加载失败: ' + error }
        }
    }

    // 更新会话顺序
    function updateSessionOrder(sessionId) {
        const session = sessionList.value.find(s => s.id === sessionId)
        if (!session) return

        // 从列表中移除该会话
        sessionList.value = sessionList.value.filter(s => s.id !== sessionId)
        
        // 分离置顶和非置顶会话
        const pinnedSessions = sessionList.value.filter(s => s.is_pinned)
        const unpinnedSessions = sessionList.value.filter(s => !s.is_pinned)
        
        // 将会话插入到适当的位置
        if (session.is_pinned) {
            // 置顶会话放在置顶列表最前面
            pinnedSessions.unshift(session)
        } else {
            // 非置顶会话放在非置顶列表最前面
            unpinnedSessions.unshift(session)
        }
        
        // 重新组合会话列表
        sessionList.value = [...pinnedSessions, ...unpinnedSessions]
    }


    // 修改置顶方法
    function pinSession(sessionId) {
        // 通过http接口发送置顶会话
        // sendPinSession(sessionId)
        const session = sessionList.value.find(s => s.id === sessionId)
        if (session) {
            session.is_pinned = true
            updateSessionOrder(sessionId)
        }
    }

    // 修改取消置顶方法
    function unpinSession(sessionId) {
        // 通过http接口发送取消置顶会话
        // sendUnpinSession(sessionId)
        const session = sessionList.value.find(s => s.id === sessionId)
        if (session) {
            session.is_pinned = false
            updateSessionOrder(sessionId)
        }
    }

    // 新增：删除会话
    function deleteSession(sessionId) {
        // 通过http接口发送删除会话
        // sendDeleteSession(sessionId)
        const index = sessionList.value.findIndex(s => s.id === sessionId)
        if (index > -1) {
            sessionList.value.splice(index, 1)
            delete messagesMap.value[sessionId]
            // 如果删除的是当前会话，切换到第一个会话
            if (sessionId === activeId.value && sessionList.value.length > 0) {
                activeId.value = sessionList.value[0].id
            }
        }
    }

    // 添加接收消息的方法
    function handleReceiveMessage(sessionId, message) {
        // 确保会话存在
        if (!messagesMap.value[sessionId]) {
            messagesMap.value[sessionId] = []
        }
        
        // 添加新消息
        messagesMap.value[sessionId].push({
            id: message.id || Date.now(),
            from: message.from,
            content: message.content,
            time: new Date().toLocaleTimeString(),
            type: message.type || 'text',
            status: 'received'
        })
        
        // 更新会话的最后消息
        const session = sessionList.value.find(s => s.id === sessionId)
        if (session) {
            session.lastMsg = message.content
            session.time = Date.now() // 添加时间戳用于排序
            // 如果不是当前会话，增加未读消息数
            if (sessionId !== activeId.value) {
                // 无需手动维护 unread，计算属性自动处理
            }
            // 更新会话顺序
            updateSessionOrder(sessionId)
        }
    }

    // init ws
    async function initializer() {
        const userStore = useUserStore()
        await userStore.fetchUserStats()
        userinfo.value = {
            email: userStore.userStats.email,
            name: userStore.userStats.name,
            avatar: userStore.userStats.avatar
        }
        if(loading.value === false) {
            loading.value = true
            addHandler('message', RecvMessageCallback)
            addHandler('send_ack', RecvSendAckCallback)
            addHandler('read_ack', RecvReadAckCallback)
            // 获取会话列表
            try {
                await fetchSessionList()
            } catch (error) {
                console.error('初始化失败', error)
                message.error('初始化失败', error)
            } finally {
                loading.value = false
            }
        }
    }


    return {
        emojis,
        followers,
        following,
        lastMessages,
        mutualFollowers,
        userinfo,
        friends,
        favoriteEmojis,
        sessionList,
        sessionTotal,
        messagesMap,
        activeId,
        activeMessages,
        unreadCounts,
        lastReadIdMap,
        fetchFriends,
        initializer,
        handleResend,
        fetchSessionMessages,
        handleSelectSession,
        handleSendMessage,
        handleSendImage,
        handleAddFavorite,
        handleSendFavorite,
        loadMoreMessages,
        pinSession,
        unpinSession,
        deleteSession,
        handleReceiveMessage,
        handleScrollToBottom,
        hasMoreSessions,
        loadingMoreSession
    }
})
